//封装请求
function request(options, app) {
  return new Promise((resolve, reject) => {
    // 获取应用实例
    if (!app) {
      app = getApp()
    }
    let userInfoHeader = app.globalData.userInfo,
      newOptions = Object.assign({},
        //默认配置
        {
          //请求头
          header: {
            "content-type": "application/json",
            ...(userInfoHeader ? {
              'access_token': userInfoHeader.token,
              'access_uid': userInfoHeader.k1UserId
            } : {}),
            ...(app.globalData.shopInfo && app.globalData.shopInfo.shopId ? {
              'shop_id': app.globalData.shopInfo.shopId
            } : {})
          }
        },
        options, {
          //固定请求域名
          url: (/^http|\.\//.test(options.url) ? options.url : app.globalData.config.server.MAIN + options.url),
          //post请求转jsonString
          // data: (options.method && options.method.toUpperCase() === "POST") ? JSON.stringify(options.data) : options.data,
          data: options.data,
          success(res) {
            if (res.data.code == 0) {
              ////请求成功
              resolve(res.data);
            } else {
              //其他异常
              reject(res.data);
            }
          },
          fail(err) {
            if (!app.globalData.isNetwork) {
              wx.showToast({
                title: '网络异常',
                icon: 'error',
                duration: 2000
              })
            }
            //请求失败
            reject(err)
          }
        });
    wx.request(newOptions);
  })
}

function post(url, params = {}, config = {}, app = null) {
  return request(Object.assign({}, {
    method: 'POST'
  }, {
    url,
    data: params,
    ...config
  }), app)
}

function get(url, params = {}, config = {}) {
  return request(Object.assign({}, {
    method: 'GET'
  }, {
    url,
    data: params,
    ...config
  }))
}

module.exports = {
  request,
  post,
  get
}